package kr.hkit.androidcomplete03.ch22;

import java.util.ArrayList;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;

public class SurfView extends SurfaceView implements Callback {

	ArrayList<Ball> arBall;
	final static int DELAY = 50;

	SurfaceHolder mHolder;
	DrawThread mThread;

	public SurfView(Context context) {
		super(context);
		mHolder=getHolder();
		mHolder.addCallback(this);
		arBall=new ArrayList<>();
	}
	public boolean onTouchEvent(MotionEvent event){
		if(event.getAction()==MotionEvent.ACTION_DOWN){
			synchronized(mHolder){
				Ball newBall=Ball.create((int)event.getX()	,(int)event.getY());
				
				arBall.add(newBall);
			}
			return true;
		}
		return false;
	}
	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		mThread=new DrawThread(mHolder);
		mThread.start();
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		if(mThread !=null){
			mThread.sizeChange(width, height);
		}
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		mThread.bExit=true;
		for(;;){
			try {
				mThread.join();
				break;
			} catch (InterruptedException e) {
			}
		}
	}

	public class DrawThread extends Thread {
		boolean bExit;
		int mWidth;
		int mHeight;
		SurfaceHolder mHolder;

		public DrawThread(SurfaceHolder mHolder) {
			super();
			this.mHolder = mHolder;
		}

		public void sizeChange(int width, int height) {
			mWidth = width;
			mHeight = height;
		}

		@Override
		public void run() {
			Canvas canvas;
			Ball b;

			while (!bExit) {
				for (int i = 0; i < arBall.size(); i++) {
					b = arBall.get(i);
					b.Move(getWidth(), getHeight());
					if (b.count > 4) {
						arBall.remove(i);
						i--;
					}
				}// end of for

				synchronized (mHolder) {
					canvas = mHolder.lockCanvas();
					if (canvas == null)
						break;
					canvas.drawColor(Color.BLACK);

					for (int i = 0; i < arBall.size(); i++) {
						arBall.get(i).Draw(canvas);
						if (bExit)
							break;
					}

				}
				mHolder.unlockCanvasAndPost(canvas);
			}
			try {
				sleep(SurfView.DELAY);
			} catch (InterruptedException e) {

			}//end of while

		}

	}
}